<?php

if(!defined('_DB_')) {
define('_DB_', 1);

/**
 * Connects to the database.
 * 
 * @return array Database connection at db_array['connection']. <br>
 * <b>false</b> on failure.
 */
function flep_db_connect() {
  include _FLEP_DB_PATH_;
  return array('connection' => @mysqli_connect($dbhost, $dbuser, $dbpass, $dbname));
}

/**
 * Check for errors.
 * Sets db_array['errno'] with the error number if any error ocurrs.
 * @param array $db_array
 * 
 * @return string Error message at db_array['error']. <br>
 * <b>false</b> if no error.
 */
function flep_db_error(&$db_array) {
  if (($err = mysqli_connect_error($db_array['connection'])) !== NULL) {
    $db_array['errno'] = mysqli_connect_errno($db_array['connection']);
    return $db_array['error'] = 'Connect Error (' . $db_array['errno'] . ') ' . $err;
  }
  if (($err = mysqli_error($db_array['connection'])) !== "") {
    $db_array['errno'] = mysqli_errno($db_array['connection']);
    return $db_array['error'] = 'Error (' . $db_array['errno'] . ') ' . $err;
  }
  return $db_array['error'] = false;
}

/**
 * Query the database.
 * 
 * @param array $db_array db_array.
 * @param string $query SQL query.
 * 
 * @return result Query result at db_array['result']<br>
 * <b>false</b> on failure.
 */
function flep_db_query(&$db_array, $query) {
  mysqli_set_charset($db_array['connection'], "utf8");
  return $db_array['result'] = mysqli_query($db_array['connection'], $query);
}

/**
 * Store the next row result on db_array['row']<br>
 * 
 * @param array $db_array
 * 
 * @return array Row data at $db_array['row'].<br>
 * <b>false</b> if no more rows.
 */
function flep_db_fetch_assoc(&$db_array) {
  return $db_array['row'] = mysqli_fetch_assoc($db_array['result']);
}

/**
 * Get row data from result <br>
 * 
 * @param array $db_array
 * 
 * @return array Row data.<br>
 * <b>false</b> if no more rows.
 */
function flep_db_row(&$db_array) {
  return $db_array['row'];
}

/**
 * Free result.
 * 
 * @param array $db_array
 */
function flep_db_free(&$db_array) {
  mysqli_free_result($db_array['result']);
}

/**
 * Close database connection.
 * 
 * @param array $db_array
 */
function flep_db_close(&$db_array) {
  mysqli_close($db_array['connection']);
}

/**
 * Get the last inserted id.
 * 
 * @param array $db_array
 */
function flep_db_last_id(&$db_array) {
  return mysqli_insert_id($db_array['connection']);
}

/**
 * Escapes especial caracters and extra spaces when inserting.
 *
 * @return string Escaped string value.
 */
function flep_db_insert_escape($value){
  return trim(str_replace(array("\\","'","%"), array("\\\\","\'","\%"), preg_replace('/\s\s+/', ' ', $value)));
}

/**
 * Escapes especial caracters and extra spaces when searching.
 *
 * @return string Escaped string value.
 */
function flep_db_escape($value){
  return str_replace(array("\\","'","%","_"), array("\\\\","\'","\%","\_"), preg_replace('/\s\s+/', ' ', $value));
}

}
?>
